package cm367;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.InputStream;
import java.util.Properties;

import javax.faces.bean.ManagedBean;

@ManagedBean
public class ReadWriteDataFile {
	private String filePath = "";
	
	public ReadWriteDataFile(String fileName) throws IOException {
//		filePath = getClass().getClassLoader().getResource("\\cm367\\Data\\" + fileName).getPath();
		Properties prop = new Properties();
		ClassLoader loader = Thread.currentThread().getContextClassLoader();
		InputStream stream = loader.getResourceAsStream("cm367.properties");
		try {
			prop.load(stream);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		filePath = prop.getProperty("db_path") + fileName;
		//filePath = "C:\\jsf\\RoomRegistration\\Data\\" + fileName;
		File file = new File(filePath);
		if(!file.exists()) {
			file.createNewFile();
			if(fileName.equals("db_Booking.txt")) {
				AppendDataFile("BookedBy|BookingDate|Period|IdVenus|VenusPrice|Fac01_Id|Fac01_Qty|Fac01_Price|Fac02_Id|Fac02_Qty|Fac02_Price|Fac03_Id|Fac03_Qty|Fac03_Price|Fac04_Id|Fac04_Qty|Fac04_Price|Fac05_Id|Fac05_Qty|Fac05_Price|TranDateTime|");
			}
		}
	}
	
	public int NumDataRow() throws IOException {
		FileReader fr = new FileReader(filePath);
		BufferedReader bf = new BufferedReader(fr);
		int numLines = 0;
		while ((bf.readLine()) != null){
			numLines++;
		}
		bf.close();
		return numLines;
	}
	
	public String[] ReadDataFile() throws IOException {
		int numLines = NumDataRow();
		
		FileReader fr = new FileReader(filePath);
		BufferedReader bf = new BufferedReader(fr);
		
		String[] dataText = new String[numLines];
		for(int lines=0; lines< numLines; lines++) {
			dataText[lines] = bf.readLine();
		}
	
		bf.close();
		return dataText;
	}
	
	public void WriteDataFile(String[] RawData) throws IOException {
		FileWriter fw = new FileWriter(filePath);
		BufferedWriter buffer = new BufferedWriter(fw); 
		for(int idx = 0; idx < RawData.length; idx++) {
			buffer.write(RawData[idx]);  
            buffer.newLine();  
            buffer.flush();  
		}
		fw.flush();
		buffer.close();
		fw.close();		
	}
	
	public void AppendDataFile(String RawData) throws IOException {
		String[] oldData = ReadDataFile();
		String[] newData = new String[oldData.length + 1];
		for(int idx=0; idx < oldData.length; idx++) {
			newData[idx] = oldData[idx];
		}
		newData[oldData.length] = RawData;
		
		FileWriter fw = new FileWriter(filePath);
		BufferedWriter buffer = new BufferedWriter(fw); 
		for(int idx = 0; idx < newData.length; idx++) {
			buffer.write(newData[idx]);  
            buffer.newLine();  
            buffer.flush();  
		}
		fw.flush();
		buffer.close();
		fw.close();		
	}
	
}
